/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.home.gui;

import com.home.common.ApplicationCommon;
import com.home.common.Constants;
import com.home.common.utils.DateUtils;
import com.home.logic.ReportLogic;
import com.home.logic.VentureLogic;
import com.home.mapping.ScorecardType;
import com.home.mapping.Venture;
import com.home.model.table.AgentRankObjTable;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.util.List;
import java.util.Map;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;

/**
 *
 * @author vi
 */
public class AVGScoreReport extends javax.swing.JInternalFrame {
    
    private ScorecardType scorecardType;
    private Venture venture;
    private BufferedImage imgChart;
    
    /**
     * Creates new form AVGScoreReport
     */
    public AVGScoreReport(ScorecardType scorecardType) {
        initComponents();
        
        this.scorecardType = scorecardType;
        
        int currentWeek = DateUtils.getCurrentWeekOfYear();
        List<Venture> ventures = new VentureLogic().findAllVenture();
        for (Venture v : ventures) {
            if (v.getVentureName().equals("Regional")) {
                ventures.remove(v);
                break;
            }
        }
        Integer type = scorecardType.getIdScorecardType();
        this.venture = ventures.get(1);
        
        Map<Integer, Double> map = new ReportLogic().getDataForAVGScoreReport(currentWeek - 4, currentWeek - 1, type, venture.getIdVenture());
        
        final CategoryDataset totalScoreOfVentureInWeeksDs = createDatasetChart1(map, venture.getVentureName());
        final JFreeChart chart = createChart(totalScoreOfVentureInWeeksDs);
        imgChart = chart.createBufferedImage(550, 240);
        lblChart.setIcon(new ImageIcon(imgChart));
        
        loadDataForTableRank(currentWeek);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        lblChart = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblRankAgent = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();

        setClosable(true);
        setTitle("AVG Score Report");
        setPreferredSize(new java.awt.Dimension(800, 650));

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Chart"));

        lblChart.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblChart, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(lblChart, javax.swing.GroupLayout.DEFAULT_SIZE, 252, Short.MAX_VALUE)
                .addContainerGap())
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Rank Agent"));

        tblRankAgent.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Rank", "Agent Name", "AVG Score"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tblRankAgent.setColumnSelectionAllowed(true);
        jScrollPane1.setViewportView(tblRankAgent);
        tblRankAgent.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        if (tblRankAgent.getColumnModel().getColumnCount() > 0) {
            tblRankAgent.getColumnModel().getColumn(0).setMinWidth(100);
            tblRankAgent.getColumnModel().getColumn(0).setPreferredWidth(100);
            tblRankAgent.getColumnModel().getColumn(0).setMaxWidth(100);
        }

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/icon/excel.png"))); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 752, Short.MAX_VALUE)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(jButton1))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 260, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        JFileChooser fc = new JFileChooser();
        int option = fc.showSaveDialog(this);
        
        if (option == JFileChooser.APPROVE_OPTION) {
            String filename = fc.getSelectedFile().getName();
            String path = fc.getSelectedFile().getParentFile().getPath();

            int len = filename.length();
            String ext = "";
            String file = "";

            if (len > 4) {
                ext = filename.substring(len - 4, len);
            }

            if (ext.equals(".xls")) {
                file = path + "\\" + filename;
            } else {
                file = path + "\\" + filename + ".xlsx";
            }
            String title = "REPORT AVG SCORE";
            
            new ApplicationCommon().writeToExcell(tblRankAgent, file,title,imgChart);
        }
    }//GEN-LAST:event_jButton1ActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblChart;
    private javax.swing.JTable tblRankAgent;
    // End of variables declaration//GEN-END:variables
    private CategoryDataset createDatasetChart1(Map<Integer, Double> mapValue, String ventureName) {
       
        final DefaultCategoryDataset dataset = new DefaultCategoryDataset();        
        
            
            for (Integer week : mapValue.keySet()) {
                Double value = mapValue.get(week);
                dataset.addValue(value, ventureName, "week "+week);
            }
        
        
        return dataset;
                
    }
    
    private JFreeChart createChart(final CategoryDataset dataset) {
        
        // create the chart...
        final JFreeChart chart = ChartFactory.createLineChart(
            "Weekly Venture AVG Score - "+scorecardType.getType(),       // chart title
            "Week",                    // domain axis label
            "",                   // range axis label
            dataset,                   // data
                PlotOrientation.VERTICAL,  // orientation
            true,                      // include legend
            true,                      // tooltips
            false                      // urls
        );

        

        chart.setBackgroundPaint(Color.white);

        final CategoryPlot plot = (CategoryPlot) chart.getPlot();
        plot.setBackgroundPaint(Color.lightGray);
        plot.setRangeGridlinePaint(Color.white);

        // customise the range axis...
        final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
        rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
        rangeAxis.setAutoRangeIncludesZero(true);

        
        
        // customise the renderer...
        final LineAndShapeRenderer renderer = (LineAndShapeRenderer) plot.getRenderer();

        plot.setRenderer(renderer);        
        
        return chart;
    }
    
    private void loadDataForTableRank(int currentWeek) {
        DefaultTableModel model = (DefaultTableModel) tblRankAgent.getModel();
        List<AgentRankObjTable> list = new ReportLogic().getDataForAgentRankReport(currentWeek - 4, currentWeek - 1, scorecardType.getIdScorecardType(), venture.getIdVenture());
        model.setRowCount(0);
        for (AgentRankObjTable obj : list) {
            model.addRow(obj.toVector());
        }
        
        DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
        centerRenderer.setHorizontalAlignment(SwingConstants.CENTER);
        tblRankAgent.getColumnModel().getColumn(0).setCellRenderer(centerRenderer);
        
        DefaultTableCellRenderer rightRenderer = new DefaultTableCellRenderer();
        rightRenderer.setHorizontalAlignment(SwingConstants.RIGHT);
        tblRankAgent.getColumnModel().getColumn(2).setCellRenderer(rightRenderer);
    }

}
